package com.wooboo.server.ext.action.traffic;



import com.wooboo.server.ext.ActionBase;
import com.wooboo.server.ext.ApiError;
import com.wooboo.server.ext.Result;
import com.wooboo.server.ext.data.Traffic;
import com.wooboo.server.ext.data.UserCompany;
import com.wooboo.server.ext.service.DbService;
import com.wooboo.server.ext.util.NumberUtil;
import com.wooboo.server.ext.util.Parameters;
import com.wooboo.server.ext.util.StringUtil;

import net.sf.json.JSONObject;

/**
 * @author www.wooboo.com.cn
 * 流量汇企业信息注册申请
 */
public class Register extends ActionBase{
	public Integer advertiserId;//广告主
	public String company_name;//公司名称
	public String city_name;//城市名称
	public String contact_mobile;//电话
	public String contact_email;//邮件
	DbService dbService = new DbService();
	public Register(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {
		advertiserId = NumberUtil.getInteger(params.getFieldValue("advertiserId"));
		if(StringUtil.isEmpty(advertiserId)){
		    throw ApiError.Type.INVALID_PARAM.toException();
		}
		
	}
	
	@Override
	public Result invokeService() throws ApiError {
		Result result = new Result();
		
		UserCompany userCompany = dbService.findCompanyById(advertiserId);
		if(null==userCompany){
			throw ApiError.Type.INVALID_PARAM.toException("账户信息不存在。");
		}
		
		if(userCompany.api_status!=Traffic.API_STATUS_APPLY){//未接入
			if(userCompany.api_status!=Traffic.API_STATUS_REGISTER){//未申请
				registerApply(userCompany);
			}
				nodeRegisterApply(userCompany);
		}
	    return result;
	}
	
	public void nodeRegisterApply(UserCompany com) throws ApiError{
		JSONObject nodeResponse = Traffic.companyNodeRegisterApply(com, Traffic.Action.insert.toString());
	    if(null==nodeResponse){
	    	throw ApiError.Type.INVALID_PARAM.toException("调用流量汇接入接口失败！");
	    }
	    String status = nodeResponse.optString("status");
		String code=nodeResponse.optString("code");
	    if("ok".equalsIgnoreCase(status) && "0".equals(code)){
	    	dbService.update4Apply(com.getId());
	    }
	}
	
	
	public void registerApply(UserCompany userCompany) throws ApiError{
        JSONObject response = Traffic.companyRegisterApply(userCompany);
		
		if(null==response){
			throw ApiError.Type.INVALID_PARAM.toException("调用流量汇注册接口失败！");
		}
		String status = response.optString("status");
		String code=response.optString("code");
		if("ok".equalsIgnoreCase(status) && "0".equals(code)){
			String company_code = response.optJSONObject("result").getString("company_code");
			dbService.update4Register(company_code, userCompany.getId());
            userCompany.setCompany_code(company_code);
            
		}else{
			throw ApiError.Type.INVALID_PARAM.toException("调用流量汇注册接口失败！status="+status+",code="+code+"】");
		}
	}
	
}
